﻿using System;
using System.Configuration.Install;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;

namespace Elderos.Utils.Services
{
	/// <summary>
	/// Base class for windows service.
	/// </summary>
	public abstract class WindowsServiceBase : ServiceBase
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="WindowsServiceBase"/> class.
		/// </summary>
		protected WindowsServiceBase()
		{
			CanPauseAndContinue = false;
		}

		/// <summary>
		/// Runs current Windows service as a console application while in DEBUG mode, otherwise as a normal Windows service.
		/// </summary>
		/// <typeparam name="TService">The type of the service.</typeparam>
		/// <param name="args">Service arguments.</param>
		public static void Run<TService>(params string[] args)
			where TService : WindowsServiceBase, new()
		{
			var service = new TService();

			if (args != null && args.Length > 0)
			{
				for (int i = 0; i < args.Length; i++)
					args[i] = args[i].Trim().ToLowerInvariant();

				string exeName = Path.GetFileName(Assembly.GetCallingAssembly().Location);
				if (args.Contains("uninstall"))
				{
					using (var installer = new AssemblyInstaller(exeName, null) {UseNewContext = true})
					{
						installer.Uninstall(null);
						return;
					}
				}
				if (args.Contains("install"))
				{
					using (var installer = new AssemblyInstaller(exeName, null) {UseNewContext = true})
					{
						installer.Install(null);
						installer.Commit(null);
						return;
					}
				}
			}
			if (Environment.UserInteractive)
				service.OnStart(args);
			else Run(service);
		}
	}
}